import { Service } from 'egg';
const md5 = require('md5')
/**
 * Test Service
 */
const crypto = require('crypto')

// DES 加密
function desEncrypt(message, key = 'YusupTurak') {
    key = key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length))
    const keyHex = Buffer.from(key)
    const cipher = crypto.createCipheriv('des-cbc', keyHex, keyHex)
    let c = cipher.update(message, 'utf8', 'base64')
    c += cipher.final('base64')
    return c
}

export default class User extends Service {

    public async Login() {
        const { ctx, app } = this;
        const { Joi } = app;
        let schema = Joi.object({
            username: Joi.string().required().max(10),
            password: Joi.string().required(),
        });
        let { error } = ctx.validate(schema, ctx.request.body);
        if (error) {
            ctx.status = 403;
            return { error: error.message };
        } else {
            let { username: user_name, password } = ctx.request.body
            let sql = `SELECT * FROM admin_user WHERE BINARY user_name = '${user_name}' AND BINARY password = '${password}'`
            let userInfo = (await app.mysql.get('Yusup').query(sql) || [])
            if (userInfo.length) {
                let token = desEncrypt(md5(password + 'YusupTurak') + Date.now().toString())
                // console.log('加密：user_token', token);

                this.ctx.cookies.set('user_token', token, {
                    maxAge: 1000 * 3600 * 24, // cookies 有效期：一天
                    httpOnly: true,
                    signed: false, // 对 Cookies 进行签名，防止用户修改
                    encrypt: false, // 对 Cookies 进行加密，同时获取时ye需要解密
                });
                return {
                    code: 200,
                    data: {
                        token: md5(password + 'YusupTurak')
                        // name: user_name,
                        // avatar: 'http://img.jj20.com/up/allimg/tx02/070920193365.jpg'
                    }
                }
            } else {
                return {
                    code: 100
                }
            }

        }
    }

    public async getUserInfo() {

        return {
            code: 200,
            data: {
                name: this.ctx.headers['x-user'],
                avatar: 'http://img.jj20.com/up/allimg/tx02/070920193365.jpg'
            }
        };
    }
    public async LogOut() {
        this.ctx.cookies.set('user_token', null);
        return {
            code: 401
        }
    }
}
